﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Core;
using Core.Interfaces;
using Core.Settings;
using DataXml;
using DataXml.CommunityFiles;
using Microsoft.Win32;

namespace TallyJ.Windows
{
  /// <summary>
  /// Interaction logic for DbTools.xaml
  /// </summary>
  public partial class DbTools
  {
    ///<summary></summary>
    public static RoutedCommand CopyToDbCommand = new RoutedCommand();

    ///<summary></summary>
    public static RoutedCommand EraseDbCommand = new RoutedCommand();

    ///<summary></summary>
    public static RoutedCommand FindXmlCommand = new RoutedCommand();

    ///<summary></summary>
    public static RoutedCommand ImportFromXmlCommand = new RoutedCommand();

    private XmlCommunity _xmlCommunity;

    private IAppSettings _settings;

    ///<summary></summary>
    public DbTools()
    {
      InitializeComponent();

      _settings = IoC.Container.Resolve<IAppSettings>();

      CommandBindings.Add(new CommandBinding(CopyToDbCommand, SaveToDb, CanSaveToDb));
      CommandBindings.Add(new CommandBinding(ImportFromXmlCommand, ImportXml, CanImportXml));
      CommandBindings.Add(new CommandBinding(EraseDbCommand, EraseDb, CanEraseDb));
      CommandBindings.Add(new CommandBinding(FindXmlCommand, FindXml, (sender, args) => args.CanExecute = true));

      btnLoadFromXml.Command = ImportFromXmlCommand;
      btnDeleteDb.Command = EraseDbCommand;
      btnCopyToDb.Command = CopyToDbCommand;
      btnFind.Command = FindXmlCommand;

      KeyDown += OnKeyDown;

      btnLoadFromXml.Focus();


      CommunityFilePath.Text = _settings.ImportXmlFilePath;
    }

    private void FindXml(object sender, ExecutedRoutedEventArgs e)
    {
      var fileDialog = new OpenFileDialog
                         {
                               CheckFileExists = true,
                               CheckPathExists = true,
                               DefaultExt = ".xml",
                               Title = "Select existing Community XML file",
                               FileName = _settings.ImportXmlFilePath,
                               Multiselect = false,
                               InitialDirectory =
                                     Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                  "TallyJ"),
                               ValidateNames = true,
                               DereferenceLinks = true,
                               AddExtension = true,
                               Filter = "TallyJ 1.x Community File (.xml)|*.xml"
                         };
      var result = fileDialog.ShowDialog();
      if (result.Value)
      {
        CommunityFilePath.Text = fileDialog.FileName;
        _settings.ImportXmlFilePath = fileDialog.FileName;
      }
    }


    private void EraseDb(object sender, ExecutedRoutedEventArgs e)
    {
      if (MessageBox.Show("Are you sure you want to erase all current data?", "Warning", MessageBoxButton.YesNoCancel)
          == MessageBoxResult.Yes)
      {
        try
        {
          IoC.Container.Resolve<ISessionProvider>().PrepareSessionFactory(true);
        }
        catch (Exception exception)
        {
          MessageBox.Show(exception.AllMessages());
        }
      }
    }

    private void CanEraseDb(object sender, CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = true;
    }

    private void OnKeyDown(object sender, KeyEventArgs args)
    {
      switch (args.Key)
      {
        case Key.Escape:
          Close();
          break;
      }
    }


    private void CanImportXml(object sender, CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = true; //_xmlCommunity == null;
    }

    private void CanSaveToDb(object sender, CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = false; // _xmlCommunity != null;
    }

    private void ImportXml(object sender, ExecutedRoutedEventArgs e)
    {
      bool successful;
      List<string> messages;

      _xmlCommunity = XmlCommunityImporter.GetXmlCommunity(out successful, out messages, CommunityFilePath.Text);

      if (!successful)
      {
        MessageBox.Show(messages.Joined("\n\r"));
      }
      else
      {
        // immediately save to DB
        SaveToDb(sender, e);
      }
    }


    private void SaveToDb(object sender, ExecutedRoutedEventArgs e)
    {
      var xmlCommunity = _xmlCommunity;

      try
      {
        XmlCommunityImporter.SaveToDb(xmlCommunity, cbAdd.IsChecked ?? false);
        MessageBox.Show("Xml Imported");
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.AllMessages("\r"));
      }
    }
  }
}